package com.weituotian.moudle.member.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.result.Result;
import com.weituotian.core.utils.ApiUtil;
import com.weituotian.core.utils.ShiroUtil;
import com.weituotian.moudle.member.entity.Member;
import com.weituotian.moudle.member.entity.enums.SexEnum;
import com.weituotian.moudle.member.entity.vo.RegVo;
import com.weituotian.moudle.member.service.IMemberService;
import com.weituotian.system.entity.enums.OpenState;
import com.weituotian.system.entity.enums.UserType;
import com.weituotian.system.service.IUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 会员注册控制器
 * Created by ange on 2017/2/14.
 */
@Controller
@RequestMapping("${memberPath}/reg")
public class RegController extends BaseController {

    private final IUserService userService;

    private final IMemberService memberService;

    @Autowired
    public RegController(IUserService userService, IMemberService memberService) {
        this.userService = userService;
        this.memberService = memberService;
    }

    @ModelAttribute
    public void initUrl(Model model) {
        String contextPath = this.getContextPath();
        model.addAttribute("doreg_url", contextPath + memberPath + "/reg/doreg");
    }

    /**
     * 注册页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String reg() {
        return "member/reg/index";
    }

    @RequestMapping(value = "/doreg", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doreg(RegVo regVo, @RequestParam(required = false) Boolean fromapp) {
        if (userService.findByLoginName(regVo.getLoginName()) != null) {
            return renderError("登录名重复");
        }
        if (userService.findByName(regVo.getName()) != null) {
            return renderError("昵称重复");
        }
        if (memberService.findByEmail(regVo.getEmail()) != null) {
            return renderError("邮箱重复");
        }

        Member member = new Member();

        member.setLoginname(regVo.getLoginName());
        member.setName(regVo.getName());
        member.setEmail(regVo.getEmail());
        member.setStatus(OpenState.OPEN);

        member.setExperience(0);
        member.setFollows(0);
        member.setFans(0);
        member.setVideos(0);
        member.setRegDate(new Date());

        //密码
        String pwd = regVo.getPassword();
        if (pwd != null && !StringUtils.isBlank(pwd)) {
            member.setPassword(DigestUtils.md5Hex(pwd));//md5密码加密
        }

        member.setUserType(UserType.MEMBER);

        //未完善资料
        member.setSex(SexEnum.UNKNOW);

        try {
            memberService.add(member);
            //分配角色,初始化为 [2普通会员]
            userService.updateRoles(member.getId(), new Integer[]{2});

            //自动登录
            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken token = new UsernamePasswordToken(member.getLoginname(), member.getPassword());
            token.setRememberMe(true);
            subject.login(token);

            //如果是从app端注册就返回自动登录成功的appuser
            if (fromapp != null && fromapp) {
                Result result = renderSuccess("注册成功");
                result.setObj(ApiUtil.getAppUser(ShiroUtil.getCurrentUser(), getAvatarPath()));
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

        Result result = renderSuccess("增加成功!");
        result.setObj(request.getContextPath() + systemPath + "/index");//首页路径
        return result;
    }
}
